@model SealManagement.Models.ProduceSign
@{
ViewData["Titel"] = "制章";
}

<h2 style="margin:20px 0">制章</h2>
<hr />
<div class="layui-tab">
	<ul class="layui-tab-title">
		<li class="layui-this" id="ukey">UKEY制章</li>
		<!-- <li id="zs">证书制章</li> -->
	</ul>
	<div class="layui-tab-content">
		<div class="layui-tab-item layui-show">
			<div class="form-group">
				<div class="col-md-offset-1 col-md-10 ">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="sealName" class="col-sm-2 control-label">印章名称</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="sealName">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="sealType" class="col-sm-2 control-label">印章类型</label>
                            <div class="col-sm-10" id="typeValue ">
                                <select id="sealType" name="sealType" class="form-control">
                                    <option value="">请选择</option>
                                    <option value="1">单位印章</option>
                                    <option value="2">个人印章</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealStartTime" class="col-sm-2 control-label">印章生效时间</label>
                            <div class="col-sm-10">
                                <input type="date" class="form-control" id="sealStartTime" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealEndTime" class="col-sm-2 control-label">印章作废时间</label>
                            <div class="col-sm-10">
                                <input type="date" class="form-control" id="sealEndTime" />
                            </div>
                        </div>
                        <input id="makerCertID" type="hidden" value="@ViewBag.makerArrayNo" class="form-control" />
                        <div class="form-group " id="ukey">
                            <label class="col-sm-2 control-label">用户UKEY</label>
                            <div class="col-sm-10" style="line-height: 30px;">
                                <select id="userCertID" name="ukeySelect" class="form-control"></select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealName" class="col-sm-2 control-label">用户ukey的PIN码</label>
                            <div class="col-sm-10">
                                <input type="password" class="form-control" id="ukeyPin">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-2">印章图片</label>
                            <div class="col-md-10">
                                <input type="hidden" id="picBase64" readonly="readonly" /><br />
                                <img id="pic" style="max-width: 100%; border: 1px solid gray;" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-2">生成方式</label>
                            <div class="col-md-10">
                                <div class="form-inline">
                                    <input type="radio" name="picGenerateType" checked="checked" value="自动生成" />
                                    <input type="button" id="generate" value="自动生成" class="btn btn-default" />
                                </div>
                                <br />
                                <div class="form-inline">
                                    <input type="radio" name="picGenerateType" value="手动上传" />
                                    <input type="file" name="upimage" id="upload_file" disabled="disabled" class="form-control" style="max-width: 260px" />
                                </div>
                            </div>
                        </div>
                        <input type="hidden" id="sealBase64" />
                        <input type="hidden" id="sealHashBase64" />
                        <input type="hidden" id="sealSigBase64" />
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <input id="btnCreate" type="button" value="创建" class="btn btn-default" />
                            </div>
                        </div>
                    </form>
					<dl id="infoDiv" class="dl-horizontal" style="display: none"></dl>
				</div>
			</div>
		</div>

		<input type="hidden" id="yz" value="" />
		<!-- <div class="layui-tab-item">
            <div class="form-group">
                <div class="col-md-offset-1 col-md-10 ">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="sealName" class="col-sm-2 control-label">印章名称</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="cer_sealName">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="sealType" class="col-sm-2 control-label">印章类型</label>
                            <div class="col-sm-10" id="cer_typeValue ">
                                <select id="cer_sealType" name="sealType" class="form-control">
                                    <option value="">请选择</option>
                                    <option value="1">单位印章</option>
                                    <option value="2">个人印章</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealStartTime" class="col-sm-2 control-label">印章生效时间</label>
                            <div class="col-sm-10">
                                <input type="date" class="form-control" id="cer_sealStartTime" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sealEndTime" class="col-sm-2 control-label">印章作废时间</label>
                            <div class="col-sm-10">
                                <input type="date" class="form-control" id="cer_sealEndTime" />
                            </div>
                        </div>
                        <input id="cer_makerCertID" type="hidden" value="@ViewBag.makerArrayNo" class="form-control" />

                        <div class="form-group " id="cer">
                            <label class="col-sm-2 control-label">用户证书</label>
                            <div class="col-sm-10" style="line-height: 30px;">
                                <button type="button" class="btn btn-default" id="ImportConfig">点击上传证书</button>
                                <span id="filename"></span>
                            </div>

                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-2">印章图片</label>
                            <div class="col-md-10">
                                <input type="hidden" id="cer_picBase64" readonly="readonly" /><br />
                                <img id="cer_pic" style="max-width: 100%; border: 1px solid gray;" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-2">生成方式</label>
                            <div class="col-md-10">
                                <div class="form-inline">
                                    <input type="radio" name="cer_picGenerateType" checked="checked" value="自动生成" />
                                    <input type="button" id="cer_generate" value="自动生成" class="btn btn-default" />
                                </div>
                                <br />
                                <div class="form-inline">
                                    <input type="radio" name="cer_picGenerateType" value="手动上传" />
                                    <input type="file" name="upimage" id="cer_upload_file" disabled="disabled" class="form-control" style="max-width: 260px" />
                                </div>
                            </div>
                        </div>
                        <input type="hidden" id="cer_sealBase64" />
                        <input type="hidden" id="cer_sealHashBase64" />
                        <input type="hidden" id="cer_sealSigBase64" />
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <input id="cer_btnCreate" type="button" value="创建" class="btn btn-default" />
                            </div>
                        </div>
                    </form>
                    <dl id="cer_infoDiv" class="dl-horizontal" style="display: none"></dl>
                </div>
            </div>
        </div> -->
	</div>
</div>
<a href="" id="target" download="a.stamp"></a>
<div id="layerPagePinCode" style="display: none">
	<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">
		请输入制章人PIN码：<br />
		<input type="password" name="ukeyPinCode" class="form-control" />
		<span id="pinError"></span>
	</div>
</div>


@section scripts {
<script src="/Content/layui/layui.js" charset="utf-8"></script>
<script src="~/js/dateformat.js"></script>
<script>
	function EnumKey(funcBack, errorCallBack) {
		var socket = new WebSocket("ws://127.0.0.1:2012/CertInfo");
		try {
			socket.onerror = errorCallBack;
			socket.onopen = function(msg) {

				//alert("连接成功！");
				socket.send("abc");
			};
			socket.onmessage = function(e) {
				if (isNumber(e.data)) {
					funcBack("");
				} else {
					//alert(e.data);
					funcBack(e.data);
				}
			};
		} catch (ex) {
			funcBack("");
		}
	}

	function GetCertAndSeal(certSN, funcBack) {
		//alert(certSN);
		var dtd = $.Deferred();
		var socket = new WebSocket("ws://127.0.0.1:2012/SealAndCertBase64");
		try {
			socket.onopen = function(msg) {
				//alert("连接成功！");
				socket.send(certSN);
			};
			socket.onmessage = function(e) {
				funcBack(e.data);
				socket.close();
				dtd.resolve();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		} finally {
			return dtd.promise();
		}
	}

	function SignByHash(strJson, funcBack) {

		//alert(strJson);
		var socket = new WebSocket("ws://127.0.0.1:2012/SignDataEx");
		try {

			socket.onopen = function(msg) {

				//alert("连接成功！");
				socket.send(strJson);
			};
			socket.onmessage = function(e) {
				funcBack(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}

	}

	function VerifyPin(strJson, funcBack) {

		//alert(strJson);
		var socket = new WebSocket("ws://127.0.0.1:2012/VerifyPin");
		try {

			socket.onopen = function(msg) {

				//alert("连接成功！");
				socket.send(strJson);
			};
			socket.onmessage = function(e) {
				funcBack(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}

	}

	function GetAuth(strJson, funcBack) {

		//alert(strJson);
		var socket = new WebSocket("ws://127.0.0.1:2012/Auth");
		try {

			socket.onopen = function(msg) {

				//alert("连接成功！");
				socket.send(strJson);
			};
			socket.onmessage = function(e) {
				funcBack(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}

	}

	function GetSerialId(certSN, funcBack) {
		var socket = new WebSocket("ws://127.0.0.1:2012/SerialId");
		try {

			socket.onopen = function(msg) {
				socket.send(certSN);
			};
			socket.onmessage = function(e) {
				funcBack(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}

	}

	function GetProducts(certSN, funcBack) {
		var socket = new WebSocket("ws://127.0.0.1:2012/Products");
		try {

			socket.onopen = function(msg) {
				socket.send(certSN);
			};
			socket.onmessage = function(e) {
				funcBack(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}
	}

	function GeneratePic(certID, funcBack) {

		//alert(strJson);
		var socket = new WebSocket("ws://127.0.0.1:2012/GeneratePic");
		try {

			socket.onopen = function(msg) {
				socket.send(certID);
			};
			socket.onmessage = function(e) {
				console.log(e);
				funcBack(e.data);
				socket.close();
			}
		} catch (ex) {
			console.log(ex);
			funcBack("");
			socket.close();
		}
	}

	function initlist(str) {
		$("select[name='ukeySelect']").each(function(index, element) {
			if (str == "") {
				$(element).empty();
			}
			var certList = $.parseJSON(str);
			var selObj = $(element);
			var maxIndex = $(element).find("option:last").index(); //获取Select最大的索引值
			//alert(maxIndex);
			for (var i = maxIndex; i >= 0; i--) {
				//alert(i);
				var exsitFlag = false;
				var currentValue = $(element).find("option:eq(" + i + ")").val();
				for (var j = 0; j < certList.CertInfolist.length; j++) {
					if (currentValue == certList.CertInfolist[j].CertID) {
						exsitFlag = true;
						break;
					}
				}
				if (exsitFlag == false) {
					$(element).find("option:eq(" + i + ")").remove();
				}
			}
			for (var i = 0; i < certList.CertInfolist.length; i++) {
				if ($(element).find("option[value='" + certList.CertInfolist[i].CertID + "']").index() == -1) {
					selObj.append("<option value='" + certList.CertInfolist[i].CertID + "'>" + certList.CertInfolist[i].CertCN +
						"</option>");
				}
			}

		});
		//$("select[name='ukeyUserSelect']").each(function (index, element) {
		//    if (str == "") {
		//        $(element).empty();
		//    }
		//    var certList = $.parseJSON(str);
		//    var selObj = $(element);
		//    var maxIndex = $(element).find("option:last").index(); //获取Select最大的索引值
		//    //alert(maxIndex);
		//    for (var i = maxIndex; i >= 0; i--) {
		//        //alert(i);
		//        var exsitFlag = false;
		//        var currentValue = $(element).find("option:eq(" + i + ")").val();
		//        for (var j = 0; j < certList.CertInfolist.length; j++) {
		//            if (currentValue == certList.CertInfolist[j].CertID) {
		//                exsitFlag = true;
		//                break;
		//            }
		//        }
		//        if (exsitFlag == false) {
		//            $(element).find("option:eq(" + i + ")").remove();
		//        }
		//    }
		//    for (var i = 0; i < certList.CertInfolist.length; i++) {
		//        if ($(element).find("option[value='" + certList.CertInfolist[i].CertID + "']").index() == -1) {
		//            selObj.append("<option value='" + certList.CertInfolist[i].CertID + "'>" + certList.CertInfolist[i].CertCN + "</option>");
		//        }
		//    }
		//});
	}

	function myPost(url, args) {
		var body = $(document.body),
			form = $("<form method='post'></form>"),
			input;
		form.attr({
			"action": url
		});
		$.each(args, function(key, value) {
			input = $("<input type='hidden'>");
			input.attr({
				"name": key
			});
			input.val(value);
			form.append(input);
		});

		form.appendTo(document.body);
		form.submit();
		document.body.removeChild(form[0]);
	}

	function isNumber(val) {

		var regPos = /^\d+(\.\d+)?$/; //非负浮点数
		var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
		if (regPos.test(val) || regNeg.test(val)) {
			return true;
		} else {
			return false;
		}
	}

	function DisplayMessage(message) {
		var mydate = new Date();
		$("#infoDiv").append("<dt>" +
			mydate.Format("hh:mm:ss") +
			"</dt><dd>" +
			message +
			"</dd>");
	}

	function Cer_DisplayMessage(message) {
		var mydate = new Date();
		$("#cer_infoDiv").append("<dt>" +
			mydate.Format("hh:mm:ss") +
			"</dt><dd>" +
			message +
			"</dd>");
	}

	// ukey计算印章哈希
	function ComputeSealHash() {
		var dtd = $.Deferred();
		var uri = "ws://127.0.0.1:2012/ComputeSealHash";
		var socket = new WebSocket(uri);
		// 建立 web socket 连接成功触发事件
		socket.onopen = function(e) {
			console.log("connected");
			var data = {
				makerCertID: $("#makerCertID").val(),
				userCertID: $("#userCertID").val(),
				picBase64: $("#picBase64").val(),
				sealName: $("#sealName").val(),
				sealType: $("#sealType").val(),
				sealStartTime: $("#sealStartTime").val(),
				sealEndTime: $("#sealEndTime").val()
			};
			// 使用 send() 方法发送数据
			socket.send(JSON.stringify(data));
		};
		// 断开 web socket 连接成功触发事件
		socket.onclose = function(e) {
			console.log("closed");
		};
		// 接收服务端数据时触发事件socket.close();
		socket.onmessage = function(e) {
			console.log(e.data);
			var retJSONObject = JSON.parse(e.data);
			if (retJSONObject.error == "Ok") {
				$("#sealBase64").val(retJSONObject.sealBase64);
				$("#sealHashBase64").val(retJSONObject.digestBase64);
				dtd.resolve();
			}
			socket.close();
		};
		socket.onerror = function(e) {
			console.log("Error: " + e.data);
		};
		return dtd.promise();
	}
	// 证书方式计算印章哈希
	function Cer_ComputeSealHash(userCertBase64) {
		var dtd = $.Deferred();
		var uri = "ws://127.0.0.1:2012/ComputeSealHash";
		var socket = new WebSocket(uri);
		// 建立 web socket 连接成功触发事件
		socket.onopen = function(e) {
			console.log("connected");
			var data = {
				makerCertID: $("#cer_makerCertID").val(),
				userCertBase64: userCertBase64,
				picBase64: $("#cer_picBase64").val(),
				sealName: $("#cer_sealName").val(),
				sealType: $("#cer_sealType").val(),
				sealStartTime: $("#cer_sealStartTime").val(),
				sealEndTime: $("#cer_sealEndTime").val()
			};
			// 使用 send() 方法发送数据
			socket.send(JSON.stringify(data));
		};
		// 断开 web socket 连接成功触发事件
		socket.onclose = function(e) {
			console.log("closed");
		};
		// 接收服务端数据时触发事件socket.close();
		socket.onmessage = function(e) {
			var retJSONObject = JSON.parse(e.data);
			console.log(retJSONObject);
			if (retJSONObject.error == "Ok") {
				$("#cer_sealBase64").val(retJSONObject.sealBase64);
				$("#cer_sealHashBase64").val(retJSONObject.digestBase64);
				dtd.resolve();
			}
			socket.close();
		};
		socket.onerror = function(e) {
			console.log("Error: " + e.data);
		};
		return dtd.promise();
	}
	// ukey计算印章签名
	function ComputeSealSig() {
		var dtd = $.Deferred();
		var uri = "ws://127.0.0.1:2012/SignDataEx";
		var socket = new WebSocket(uri);
		socket.onopen = function(e) {
			console.log("connected");
			var data = {
				certId: $("#makerCertID").val(),
				hashBase64: $("#sealHashBase64").val(),
				strPin: "111111"
			};
			socket.send(JSON.stringify(data));
		};
		socket.onclose = function(e) {
			console.log("closed");
		};
		socket.onmessage = function(e) {
			console.log(e.data);
			var retJSONObject = JSON.parse(e.data);
			if (retJSONObject.error == "Ok") {
				$("#sealSigBase64").val(retJSONObject.SigBase64);
				dtd.resolve(e.data);
			}
			socket.close();
		};
		socket.onerror = function(e) {
			console.log("Error: " + e.data);
		};
		return dtd.promise();
	}
	// 证书计算印章签名
	function cer_ComputeSealSig() {
		var dtd = $.Deferred();
		var uri = "ws://127.0.0.1:2012/SignDataEx";
		var socket = new WebSocket(uri);
		socket.onopen = function(e) {
			console.log("connected");
			var data = {
				certId: $("#cer_makerCertID").val(),
				hashBase64: $("#cer_sealHashBase64").val(),
				strPin: "111111"
			};
			socket.send(JSON.stringify(data));
		};
		socket.onclose = function(e) {
			console.log("closed");
		};
		socket.onmessage = function(e) {
			console.log(e.data);
			var retJSONObject = JSON.parse(e.data);
			if (retJSONObject.error == "Ok") {
				$("#cer_sealSigBase64").val(retJSONObject.SigBase64);
				dtd.resolve(e.data);
			}
			socket.close();
		};
		socket.onerror = function(e) {
			console.log("Error: " + e.data);
		};
		return dtd.promise();
	}
	// ukey计算最终印章数据
	function ComputeSeal() {
		var dtd = $.Deferred();
		var uri = "ws://127.0.0.1:2012/ComputeSeal";
		var socket = new WebSocket(uri);
		socket.onopen = function(e) {
			console.log("connected");
			var data = {
				sealWithoutSigBase64: $("#sealBase64").val(),
				sigBase64: $("#sealSigBase64").val()
			};
			socket.send(JSON.stringify(data));
		};
		socket.onclose = function(e) {
			console.log("closed");
		};
		socket.onmessage = function(e) {
			console.log(e.data);
			var retJSONObject = JSON.parse(e.data);
			console.log(22222);
			console.log(retJSONObject);
			if (retJSONObject.error == "Ok") {
				$("#sealBase64").val(retJSONObject.sealBase64);
				dtd.resolve();
			}
			socket.close();
		};
		socket.onerror = function(e) {
			console.log("Error: " + e.data);
		};
		return dtd.promise();
	}
	//**************************************************************************************
	function load() {
		document.getElementById("target").click();
	}

	function getBlob(base64) {
		console.log(base64);
		console.log(getContentType(base64))
		return b64toBlob(base64, getContentType(base64));
	}

	function getContentType(base64) {
		var arr = /data:([^;]*);/i.exec(base64);
		console.log(arr);
		return arr;
	}

	//function getData(base64) {
	//    return base64.substr(base64.indexOf("base64,") + 7, base64.length);
	//}

	function b64toBlob(b64Data, contentType, sliceSize) {
		contentType = contentType || '';
		sliceSize = sliceSize || 512;
		console.log(b64Data);
		var byteCharacters = atob(b64Data);
		console.log(byteCharacters);
		var byteArrays = [];

		for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
			var slice = byteCharacters.slice(offset, offset + sliceSize);

			var byteNumbers = new Array(slice.length);
			for (var i = 0; i < slice.length; i++) {
				byteNumbers[i] = slice.charCodeAt(i);
			}

			var byteArray = new Uint8Array(byteNumbers);

			byteArrays.push(byteArray);
		}

		var blob = new Blob(byteArrays, {
			type: contentType
		});
		return blob;
	}
	//**************************************************************************************
	// 证书方式计算最终印章数据
	function Cer_ComputeSeal() {
		var dtd = $.Deferred();
		var uri = "ws://127.0.0.1:2012/ComputeSeal";
		var socket = new WebSocket(uri);
		socket.onopen = function(e) {
			console.log("connected");
			var data = {
				sealWithoutSigBase64: $("#cer_sealBase64").val(),
				sigBase64: $("#cer_sealSigBase64").val()
			};
			socket.send(JSON.stringify(data));
		};
		socket.onclose = function(e) {
			console.log("closed");
		};
		socket.onmessage = function(e) {
			var retJSONObject = JSON.parse(e.data);
			console.log(111111);
			console.log(retJSONObject);
			if (retJSONObject.error == "Ok") {
				$("#cer_sealBase64").val(retJSONObject.sealBase64);
				var blob = getBlob(retJSONObject.sealBase64);
				console.log(45454545445);
				console.log(URL.createObjectURL(blob));
				var downLoad = document.querySelectorAll('#target')[0];
				downLoad.setAttribute('href', URL.createObjectURL(blob));
				load();
				//downLoad.setAttribute('href', URL.createObjectURL(blob));
				dtd.resolve();
			}
			socket.close();
		};
		socket.onerror = function(e) {
			console.log("Error: " + e.data);
		};
		return dtd.promise();
	}
	// ukey写入印章数据
	function WriteUkey() {
		var dtd = $.Deferred();
		var uri = "ws://127.0.0.1:2012/WriteUkey";
		var socket = new WebSocket(uri);
		socket.onopen = function(e) {
			console.log("connected");
			var data = {
				certID: $("#userCertID").val(),
                fileName: "_HNCA_GMSEAL_",
				dataBase64: $("#sealBase64").val()
			};
			console.log(data);
			socket.send(JSON.stringify(data));
		};
		socket.onclose = function(e) {
			console.log("closed");
		};
		socket.onmessage = function(e) {
			console.log(3333333333);
			console.log(e.data);
            if (e.data == "Ok") {
                dtd.resolve();
            } else {
                let str = e.data.substring(e.data.charAt(':'));
                if (Number.parseInt(str) == 0x0A000006) {
                    layer.msg("图片太大,请上传正确的图片");
                } else if (Number.parseInt(str) == 0x0A00002D) {
                    layer.msg("权限不足");
                } else {
                    layer.msg("印章未写入");
                }
$("#infoDiv").html("")
                $("#btnCreate").attr("disabled", false);
                
            }
			socket.close();
		};
		socket.onerror = function(e) {
			console.log("Error: " + e.data);
		};
		return dtd.promise();
	}
	//Base64编码
	function Base64() {
		// private property
		_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

		// public method for encoding
		this.encode = function(input) {
			var output = "";
			var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
			var i = 0;
			input = _utf8_encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output = output +
					_keyStr.charAt(enc1) +
					_keyStr.charAt(enc2) +
					_keyStr.charAt(enc3) +
					_keyStr.charAt(enc4);
			}
			return output;
		};

		// public method for decoding
		this.decode = function(input) {
			var output = "";
			var chr1, chr2, chr3;
			var enc1, enc2, enc3, enc4;
			var i = 0;
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
			while (i < input.length) {
				enc1 = _keyStr.indexOf(input.charAt(i++));
				enc2 = _keyStr.indexOf(input.charAt(i++));
				enc3 = _keyStr.indexOf(input.charAt(i++));
				enc4 = _keyStr.indexOf(input.charAt(i++));
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
				output = output + String.fromCharCode(chr1);
				if (enc3 != 64) {
					output = output + String.fromCharCode(chr2);
				}
				if (enc4 != 64) {
					output = output + String.fromCharCode(chr3);
				}
			}
			output = _utf8_decode(output);
			return output;
		};

		// private method for UTF-8 encoding
		_utf8_encode = function(string) {
			string = string.replace(/\r\n/g, "\n");
			var utftext = "";
			for (var n = 0; n < string.length; n++) {
				var c = string.charCodeAt(n);
				if (c < 128) {
					utftext += String.fromCharCode(c);
				} else if ((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				} else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}

			}
			return utftext;
		};

		// private method for UTF-8 decoding
		_utf8_decode = function(utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
			while (i < utftext.length) {
				c = utftext.charCodeAt(i);
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				} else if ((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i + 1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				} else {
					c2 = utftext.charCodeAt(i + 1);
					c3 = utftext.charCodeAt(i + 2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
			}
			return string;
		};
	}

	//外部加密
	function ExternalEncrypt(Json, funcBack) {
		console.log(Json)
		var socket = new WebSocket("ws://127.0.0.1:2012/CustomizeEnvelope");
		try {

			socket.onopen = function(msg) {
				socket.send(Json);
			};
			socket.onmessage = function(e) {
				console.log(e.data, "加密");
				funcBack(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}

	}

	function EncryptCertList(back) {
		var socket = new WebSocket("ws://127.0.0.1:2012/EncryptCertList");
		try {

			socket.onopen = function(msg) {
				socket.send("1");
			};
			socket.onmessage = function(e) {
				console.log(e.data)
				back(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}
	}

	function EncryptCertBase64(str, back) {
		var socket = new WebSocket("ws://127.0.0.1:2012/EncryptCertBase64");
		try {

			socket.onopen = function(msg) {
				socket.send(str);
			};
			socket.onmessage = function(e) {
				// console.log(e.data)
				back(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}
	}
	var layer = null;

	$(function() {
		$.ajax({
			url: "/InfoLog/ReturnValidateCode",
			type: 'get',

			success: function(data) {
				$("#yz").val(data.validateCode);
			},
		});
		var ValidateCode = null;
		var base64 = new Base64();
		var layer = null;
		var userCertBase64 = "";
		var cer_userCertBase64 = "";
		layui.use(['upload', 'layer', 'element'], function() {
			var upload = layui.upload;
			var element = layui.element;
			layer = layui.layer;
			//执行实例
			upload.render({
				elem: '#ImportConfig',
				url: '/api/upload/',
				auto: false //选择文件后不自动上传
					,
				accept: 'file',
				multiple: false
					//, bindAction: '#testListAction' //指向一个按钮触发上传
					,
				choose: function(obj) {
					var files = obj.pushFile();
					obj.preview(function(index, file, result) {
						console.log(index);
						console.log(file);
						$("#filename").html(file.name);
						console.log(result); //得到文件base64编码，比如图片
						cer_userCertBase64 = result.split("base64,")[1];
						console.log(cer_userCertBase64);

					});
				}
			});
		});
		$("#ukey").click(() => {
			$.ajax({
				url: "/InfoLog/ReturnValidateCode",
				type: 'get',

				success: function(data) {
					$("#yz").val(data.validateCode);
				}
			});

		});
		$("#zs").click(() => {
			$.ajax({
				url: "/InfoLog/ReturnValidateCode",
				type: 'get',

				success: function(data) {
					$("#yz").val(data.validateCode);
				},
			});
		});
		EnumKey(function(data) {
				initlist(data);
			},
			function() {
				layer.alert("未安装UKEY支持服务！");
			});
		// UKEY制章
		$("input[name='picGenerateType']").click(function() {
			var picGenerateType = $("input[name='picGenerateType']:checked").val();
			if (picGenerateType == "自动生成") {
				$("#generate").attr("disabled", false);
				$("#upload_file").attr("disabled", true);
			} else {
				$("#generate").attr("disabled", true);
				$("#upload_file").attr("disabled", false);
			}
		});
		// 证书制章
		// $("input[name='cer_picGenerateType']").click(function () {
		//     var picGenerateType = $("input[name='cer_picGenerateType']:checked").val();
		//     if (picGenerateType == "自动生成") {
		//         $("#cer_generate").attr("disabled", false);
		//         $("#cer_upload_file").attr("disabled", true);
		//     } else {
		//         $("#cer_generate").attr("disabled", true);
		//         $("#cer_upload_file").attr("disabled", false);
		//     }
		// });
		// UKEY制章
		$("#generate").click(function() {
			var certSN = $("#userCertID").val();
			console.log(certSN);
			GeneratePic(certSN,
				function(value) {
					var retJObject  = JSON.parse(value);
					console.log(retJObject);
					if (retJObject.error == "Ok") {
						var picBase64 = retJObject.picBase64;
						$("#pic").attr("src", "data:image/png;base64," + picBase64);
						$("#picBase64").val(picBase64);
					} else {
                                layer.msg(retJObject.error)
                            }
				});
		});
		// 证书制章
		// $("#cer_generate").click(function () {
		//     var certSN = cer_userCertBase64;
		//     console.log(certSN);
		//     GeneratePic(certSN,
		//         function (value) {
		//             var retJObject = JSON.parse(value);
		//             console.log(retJObject);
		//             if (retJObject.error == "Ok") {
		//                 var picBase64 = retJObject.picBase64;
		//                 $("#cer_pic").attr("src", "data:image/png;base64," + picBase64);
		//                 $("#cer_picBase64").val(picBase64);
		//             } else {
		//                 layer.msg(retJObject.error);
		//             }
		//         });
		// });
		// UKEY制章
		$("#upload_file").change(function() {
			var file = $('#upload_file').get(0).files[0];
			console.log(file);
			console.log($('#cer_upload_file').get(0));
			if (!/image\/\w+/.test(file.type)) {
				layer.alert("请确保文件为图像类型");
				return;
			}
			var r = new FileReader(); //本地预览
			r.onload = function() {
				$("#pic").attr("src", r.result);
				$("#picBase64").val(r.result.substring(r.result.indexOf(',') + 1));
			};
			r.readAsDataURL(file); //Base64
		});
		// 证书制章
		// $("#cer_upload_file").change(function () {
		//     var file = $('#cer_upload_file').get(0).files[0];
		//     console.log(file);
		//     console.log($('#cer_upload_file').get(0));
		//     if (!/image\/\w+/.test(file.type)) {
		//         layer.alert("请确保文件为图像类型");
		//         return;
		//     }
		//     var r = new FileReader(); //本地预览
		//     r.onload = function () {
		//         $("#cer_pic").attr("src", r.result);
		//         $("#cer_picBase64").val(r.result.substring(r.result.indexOf(',') + 1));
		//     };
		//     r.readAsDataURL(file); //Base64
		// });
        $('#btnCreate').click(function () {
           
			var sealName = $("#sealName").val();
			var sealType = $("#sealType").val();
			var sealStartTime = $("#sealStartTime").val();
			var sealEndTime = $("#sealEndTime").val();
			var imgsrc = $("#pic")[0].src;
			console.log(112131);
			console.log(imgsrc);
			if (sealName == '' || $("#ukeyPin").val()==''|| (sealType != 1 && sealType != 2) || sealStartTime == "" || sealEndTime == "" || imgsrc ==
				"") {
				layer.msg("请完善信息！")
				return;
			}
			console.log(sealName, sealType, sealStartTime, sealEndTime, imgsrc);
			$("#infoDiv").empty();
			$("#infoDiv").fadeIn();
            $("#btnCreate").attr("disabled", true);
            VerifyPin(JSON.stringify({
                CertID: $("#userCertID").val(),
                Pin: $("#ukeyPin").val(),
            }),
                function (verifyPinRet) {
                    if (verifyPinRet != "Ok") {

                        DisplayMessage("用户ukey的PIN码验证失败");
                            $("#btnCreate").attr("disabled", false);
                    } else {
                        DisplayMessage("正在获取UKEY证书");
                        if ($("#makerCertID").val() == $("#userCertID").val()) {
                            DisplayMessage("制章人UKEY与用户UKEY不能为同一个");
                            $("#btnCreate").attr("disabled", false);
                            return;
                        }
                        console.log($("#makerCertID").val());
                        console.log($("#userCertID").val());
                        var makerCertBase64 = "";

                        var certSN = $("#makerCertID").val();
                        var dtd1 = GetCertAndSeal(certSN, function (certAndSeal) {
                            console.log(certSN);
                            console.log(certAndSeal);
                            var certAndSealJObject = JSON.parse(certAndSeal);
                            if (certAndSealJObject.CertBase64.length != 0) {
                                makerCertBase64 = certAndSealJObject.CertBase64;
                            }
                        });
                        var certUserSN = $("#userCertID").val();
                        var dtd2 = GetCertAndSeal(certUserSN, function (certAndSeal) {
                            var certAndSealJObject = JSON.parse(certAndSeal);
                            if (certAndSealJObject.CertBase64.length != 0) {
                                userCertBase64 = certAndSealJObject.CertBase64;
                            }
                        });
                        console.log(dtd1);
                        console.log(dtd2);
                        DisplayMessage("正在验证PIN码");
                        var dtd = $.Deferred();
                        $.when(dtd1, dtd2).done(function () {
                            if (makerCertBase64 == "") {
                                DisplayMessage("未插入制章人UKEY，无法完成操作");

                                $("#btnCreate").attr("disabled", false);
                                return;
                            }
                            layer.open({
                                type: 1,
                                title: false //不显示标题栏
                                ,
                                closeBtn: true,
                                area: '300px;',
                                shade: 0.8,
                                id: 'LAY_InputPin' //设定一个id，防止重复弹出
                                ,
                                btn: ['确定'],
                                btnAlign: 'c',
                                moveType: 1 //拖拽模式，0或者1
                                ,
                                content: $("#layerPagePinCode").html(),
                                yes: function (index, layero) {
                                    VerifyPin(JSON.stringify({
                                        CertID: $("#makerCertID").val(),
                                        Pin: layero.find("input[name='ukeyPinCode']").val()
                                    }),
                                        function (verifyPinRet) {
                                            if (verifyPinRet != "Ok") {
                                                layero.find("#pinError").html("Pin码错误，请重新输入");
                                                layero.find("input[name='ukeyPinCode']").val("");
                                            } else {
                                                $("input[name='ukeyPinCode']")
                                                    .val(layero.find("input[name='ukeyPinCode']").val());
                                                layer.close(index);
                                                dtd.resolve();
                                            }
                                        });
                                },
                                cancel: function () {
                                    $("#btnCreate").attr("disabled", false);
                                }
                            });
                        });
                        DisplayMessage("正在制章...");
                        dtd.done(function () {
                            ComputeSealHash().done(function () {
                                DisplayMessage("计算哈希值...");
                                ComputeSealSig().done(function () {
                                    DisplayMessage("签名印章数据...");
                                    ComputeSeal().done(function () {
                                        DisplayMessage("生成印章结构...");
                                        WriteUkey().done(function () {
                                            DisplayMessage("将印章结构写入ukey中...");
                                            EncryptCertList((data) => {
                                                DisplayMessage("获取加密证书")
                                                data = JSON.parse(data);
                                                // let CertID = data.CertInfolist[0].CertID;

                                                let CertID = null;
                                                //获取选中的ID值
                                                $(data.CertInfolist).each((i, value) => {
                                                    if (value.CertCN == $("#userCertID option:selected").text()) {
                                                        CertID = value.CertID;
                                                        return;
                                                    }
                                                })
                                                EncryptCertBase64(CertID, (b64) => {
                                                    b64 = JSON.parse(b64);
                                                    let certBase64 = null;
                                                    // if(b64.error=="")
                                                    b64.error == "Ok" ? certBase64 = b64.certBase64 : null;

                                                    if (certBase64 != null) {
                                                        var SealBase64 = {
                                                            CertID: CertID,
                                                            DataBase64: $("#sealBase64").val(),
                                                            ExternalCertBase64: certBase64
                                                        }
                                                        ExternalEncrypt(JSON.stringify(SealBase64), (data) => {
                                                            DisplayMessage("加密数据...");
                                                            data = JSON.parse(data);
                                                            if (data.error == "Ok") {
                                                                var sealBase64salt = data.contentBase64;
                                                                var str = JSON.stringify({
                                                                    ProduceSign: {
                                                                        sealName: $("#sealName").val(),
                                                                        sealType: $("#sealType").val(),
                                                                        startTime: $("#sealStartTime").val(),
                                                                        endTime: $("#sealEndTime").val(),
                                                                        makerCertSN: certSN,
                                                                        makerCertBase64: makerCertBase64,
                                                                        userCertSN: certUserSN,
                                                                        userCertBase64: userCertBase64,
                                                                        sealBase64: sealBase64salt,
																		SealImage:$("#picBase64").val()
                                                                    },
                                                                    ValidateCode: $("#yz").val(),
                                                                    
                                                                        UserCN:$("#userCertID option:selected").text()
                                                                });
                                                                var External = {
                                                                    CertID: CertID,
                                                                    //编码
                                                                    DataBase64: base64.encode(str),
                                                                };
                                                                ExternalEncrypt(JSON.stringify(External), (data) => {
                                                                    data = JSON.parse(data);
                                                                    if (data.error == "Ok") {
                                                                        var dataToPost = {
                                                                            // ArrayNo: CertID,
                                                                            EncryptData: data.contentBase64
                                                                        };
                                                                        $.post("/ProduceSign/Create",
                                                                            dataToPost,
                                                                            function (ret) {
                                                                                if (ret.state == "200") {
                                                                                    DisplayMessage(ret.message);
                                                                                } else {
                                                                                    DisplayMessage(ret.message);
                                                                                }
                                                                            });
                                                                        $("#btnCreate").attr("disabled", false);

                                                                    } else {
                                                                        DisplayMessage(data.error);
                                                                    }
                                                                });
                                                            } else {

                                                                DisplayMessage(data.error);
                                                            }

                                                        });

                                                    } else {
                                                        
                                                    DisplayMessage(b64.error);
                                                    }
                                                });


                                            })

                                        });
                                    });
                                });
                            });
                        });
                    }
                });
            

			//var ArrayNo = $('#ArrayNo').val();
			//var Certificator = $('#Certificator').val();
			//var Remark = $('#Remark').val();
			//var ukeySelect = $('#ukeySelect').val();


			//var ukeyInput =
			//{
			//    ArrayNo: ArrayNo,
			//    Certificator: Certificator,
			//    sealHashBase64: sealHashBase64,
			//    Remark: Remark,
			//    ukeySelect: ukeySelect
			//};
			//DisplayMessage("正在向服务器发送验证数据");
			//myPost("/Login/SignMakerLogin", ukeyInput);

		});
		//             $('#cer_btnCreate').click(function () {
		//                 var sealName = $("#cer_sealName").val();
		//                 var sealType = $("#cer_sealType").val();
		//                 var sealStartTime = $("#cer_sealStartTime").val();
		//                 var sealEndTime = $("#cer_sealEndTime").val();
		//                 var imgsrc = $("#cer_pic")[0].src;
		//                 if (sealName == '' || (sealType != 1 && sealType != 2) || sealStartTime == "" || sealEndTime == "" || imgsrc ==
		//                     "") {
		//                     layer.msg("请完善信息！")
		//                     return;
		//                 }
		//                 console.log(sealName, cer_userCertBase64, sealType, sealStartTime, sealEndTime, imgsrc);
		//                 $("#cer_infoDiv").empty();
		//                 $("#cer_infoDiv").fadeIn();
		//                 $("#cer_btnCreate").attr("disabled", true);
		//                 Cer_DisplayMessage("正在获取UKEY证书");
		//                 //if ($("#cer_makerCertID").val() == $("#cer_userCertID").val()) {
		//                 //    DisplayMessage("制章人UKEY与用户UKEY不能为同一个");
		//                 //    $("#cer_btnCreate").attr("disabled", false);
		//                 //    return;
		//                 //}
		//                 console.log($("#cer_makerCertID").val());
		//                 //console.log($("#cer_userCertID").val());
		//                 var makerCertBase64 = "";
		// 
		//                 var certSN = $("#cer_makerCertID").val();
		//                 var dtd1 = GetCertAndSeal(certSN, function (certAndSeal) {
		//                     console.log(certSN);
		//                     console.log(certAndSeal);
		//                     var certAndSealJObject = JSON.parse(certAndSeal);
		//                     if (certAndSealJObject.CertBase64.length != 0) {
		//                         makerCertBase64 = certAndSealJObject.CertBase64;
		//                     }
		//                 });
		//                 console.log(dtd1);
		//                 //    var certUserSN = $("#userCertID").val();
		//                 //    var dtd2 = GetCertAndSeal(certUserSN, function (certAndSeal) {
		//                 //        var certAndSealJObject = JSON.parse(certAndSeal);
		//                 //        if (certAndSealJObject.CertBase64.length != 0) {
		//                 //            cer_userCertBase64 = certAndSealJObject.CertBase64;
		//                 //        }
		//                 //    });
		//                 Cer_DisplayMessage("正在验证PIN码");
		//                 var dtd = $.Deferred();
		//                 $.when(dtd1).done(function () {
		//                     if (makerCertBase64 == "") {
		//                         Cer_DisplayMessage("未插入制章人UKEY，无法完成操作");
		//                         $("#cer_btnCreate").attr("disabled", false);
		//                         return;
		//                     }
		//                     layer.open({
		//                         type: 1,
		//                         title: false //不显示标题栏
		//                         ,
		//                         closeBtn: true,
		//                         area: '300px;',
		//                         shade: 0.8,
		//                         id: 'LAY_InputPin' //设定一个id，防止重复弹出
		//                         ,
		//                         btn: ['确定'],
		//                         btnAlign: 'c',
		//                         moveType: 1 //拖拽模式，0或者1
		//                         ,
		//                         content: $("#layerPagePinCode").html(),
		//                         yes: function (index, layero) {
		//                             VerifyPin(JSON.stringify({
		//                                 CertID: certSN,
		//                                 Pin: layero.find("input[name='ukeyPinCode']").val()
		//                             }),
		//                                 function (verifyPinRet) {
		//                                     if (verifyPinRet != "Ok") {
		//                                         layero.find("#pinError").html("Pin码错误，请重新输入");
		//                                         layero.find("input[name='ukeyPinCode']").val("");
		//                                     } else {
		//                                         $("input[name='ukeyPinCode']")
		//                                             .val(layero.find("input[name='ukeyPinCode']").val());
		//                                         layer.close(index);
		//                                         dtd.resolve();
		//                                     }
		//                                 });
		//                         },
		//                         cancel: function () {
		//                             $("#cer_btnCreate").attr("disabled", false);
		//                         }
		//                     });
		//                 });
		//                 Cer_DisplayMessage("正在制章...");
		//                 dtd.done(function () {
		//                     console.log(1)
		//                     Cer_ComputeSealHash(cer_userCertBase64).done(function () {
		//                         cer_ComputeSealSig().done(function () {
		//                             Cer_ComputeSeal().done(function () {
		// 									EncryptCertList((data) => {
		//                                         data = JSON.parse(data);
		//                                     let CertID = null;
		//                                     //获取选中的ID值
		//                                     $(data.CertInfolist).each((i, value) => {
		//                                         if (value.CertCN == $("#userCertID option:selected").text()) {
		//                                             CertID = value.CertID;
		//                                             return;
		//                                         }
		//                                     })
		//                                         EncryptCertBase64(CertID, (b64) => {
		//                                         b64 = JSON.parse(b64);
		//                                         let certBase64 = null;
		//                                         
		//                                             console.log(b64, '2222')
		//                                             // if(b64.error=="")
		//                                         b64.error == "Ok" ? certBase64 = b64.certBase64 : null;
		//                                         
		//                                         if (certBase64 != null) {
		//                                             var SealBase64 = {
		//                                                 CertID:CertID,
		//                                                 DataBase64: $("#cer_sealBase64").val(),
		// 												ExternalCertBase64: certBase64
		//                                             }
		//                                             ExternalEncrypt(JSON.stringify(SealBase64), (data) => {
		//                                                 data = JSON.parse(data);
		// 												if (data.error == "Ok") {
		// 													var sealBase64salt = data.contentBase64;
		// 													var str = JSON.stringify({
		// 													    ProduceSign:{
		// 													        sealName: $("#cer_sealName").val(),
		// 													       sealType: $("#cer_sealType").val(),
		// 													       startTime: $("#cer_sealStartTime").val(),
		// 													       endTime: $("#cer_sealEndTime").val(),
		// 													        makerCertSN: certSN,
		// 													        makerCertBase64: makerCertBase64,
		// 													        userCertSN: certUserSN,
		// 													        userCertBase64: userCertBase64,
		// 													        sealBase64: sealBase64salt
		// 													    },
		// 													    ValidateCode:$("#yz").val()
		// 													});
		// 													var External = {
		// 													    CertID: CertID,
		// 													    //编码
		// 													    DataBase64: base64.encode(str),
		// 													};
		// 													ExternalEncrypt(JSON.stringify(External), (data) => {
		// 													    data = JSON.parse(data);
		// 													    if (data.error == "Ok") {
		// 													        var dataToPost = {
		// 													            // ArrayNo: CertID,
		// 													            EncryptData: data.contentBase64
		// 													        };
		// 													        $.post("/ProduceSign/Create",
		// 													            dataToPost,
		// 													            function (ret) {
		// 																	// if(ret.state=="200"){
		// 																		
		// 																		    DisplayMessage(ret.message);
		// 																	// }
		// 													            });
		// 													        $("#cer_btnCreate").attr("disabled", false);
		// 													
		// 													    }
		// 													});
		// 												}
		//                                                 
		//                                             });
		// 
		//                                         }
		//                                     });
		//                                 
		//                             });
		//                         });
		//                     });
		//                 });

		//    //var ArrayNo = $('#ArrayNo').val();
		//    //var Certificator = $('#Certificator').val();
		//    //var Remark = $('#Remark').val();
		//    //var ukeySelect = $('#ukeySelect').val();


		//    //var ukeyInput =
		//    //{
		//    //    ArrayNo: ArrayNo,
		//    //    Certificator: Certificator,
		//    //    sealHashBase64: sealHashBase64,
		//    //    Remark: Remark,
		//    //    ukeySelect: ukeySelect
		//    //};
		//    //DisplayMessage("正在向服务器发送验证数据");
		//    //myPost("/Login/SignMakerLogin", ukeyInput);

		// });
	});
</script>
}
